<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-field
        v-model="fromData.email"
        :placeholder="$t('message.account.emailPlaceholder')"
        :rules="[{ required: true, message: $t('message.account.emailPlaceholder') }]"
      />
      <van-field
        v-model="fromData.password"
        type="password"
        :placeholder="$t('message.account.passwordPlaceholder')"
        :rules="[{ required: true, message: $t('message.account.passwordPlaceholder') }]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="loading.signIn"
          >{{$t('message.account.accountBtnText')}}</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, toRefs } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store'
import { useI18n } from 'vue-i18n'
import { formatAxis } from '@/utils/formatTime'
import { Toast } from 'vant'
import { initFrontEndControlRoutes } from '@/router/frontEnd'
import { initBackEndControlRoutes } from '@/router/backEnd'

const useLogin = (signInSuccess: any) => {
  const state = reactive({
    email: '',
    password: '',
    isShowPassword: false,
    fromData: {
      email: '',
      password: '',
    },
    loading: {
      signIn: false,
    },
  })
  const store = useStore()

  const onSubmit = async () => {
    state.loading.signIn = true
    await store.dispatch('user/login', state.fromData)
    if (!store.state.themeConfig.themeConfig.isRequestRoutes) {
      // 前端控制路由，2、请注意执行顺序
      await initFrontEndControlRoutes()
    } else {
      // 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
      // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
      await initBackEndControlRoutes()
      // 执行完 initBackEndControlRoutes，再执行 signInSuccess
    }
    signInSuccess(state)
  }

  return {
    ...toRefs(state),
    onSubmit,
  }
}
const useSignInSuccess = () => {
  const { t } = useI18n()
  const route = useRoute()
  const router = useRouter()
  // 登录成功后的跳转
  const signInSuccess = (state: any) => {
    const currentTime = computed(() => {
      return formatAxis(new Date())
    })
    // 初始化登录成功时间问候语
    let currentTimeInfo = currentTime.value
    // 登录成功，跳到转首页
    // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
    // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
    if (route.query?.redirect) {
      router.push({
        path: route.query.redirect as string,
        query:
          Object.keys(route.query?.params || {}).length > 0
            ? JSON.parse(route.query?.params as string)
            : '',
      })
    } else {
      router.push('/')
    }
    // 登录成功提示
    setTimeout(() => {
      // 关闭 loading
      state.loading.signIn = true
      const signInText = t('message.signInText')
      Toast.success(`${currentTimeInfo}，${signInText}`)
    }, 300)
  }
  return {
    signInSuccess,
  }
}
export default defineComponent({
  name: 'LoginIndex',
  setup() {
    const { signInSuccess } = useSignInSuccess()
    return {
      ...useLogin(signInSuccess),
    }
  },
})
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-form {
    width: 300px;
    background: #fff;
    padding: 20px;
    border-radius: 5px;
  }
  .login-btn {
    width: 100%;
  }
}
</style>
